package com.fancon.android.gardenjokesx.dialog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.M04_7Activity;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;

public class M04_5Dialog extends Dialog {

	private Button btnReport, btnSave;
	private Button btnCancel;
	private Activity mContext;
	private Photo photo;
	private String currentUserId;
	private String blockId;
	private String imagePath;
	private String saveName = "jorke_image";
	private Button btnSharePhoto;
	private Bundle bundle;
	public M04_5Dialog(Context group, Activity context, Photo photo, Bundle b) {
		super(group, android.R.style.Theme_Translucent_NoTitleBar);
		// TODO Auto-generated constructor stub
		mContext = context;
		this.photo = photo;
		this.bundle = b;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.m04_5);
		setCancelable(true);
		getWindow().setGravity(Gravity.BOTTOM);
		currentUserId = UserUtil.getInfoUserLogin(mContext).getUser_id();
		
		if(photo.getUser() != null){
			blockId = photo.getUser().getUser_id();
		}
		btnReport = (Button) findViewById(R.id.m04_5_btnReport);
		btnSave = (Button) findViewById(R.id.m04_5_btnSave);
		btnSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				saveImage();
			}
		});
		btnReport.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//@binhbt-comment
				//Dialog dialogReason = new M041DialogReportUser(mContext.getParent()!= null?mContext.getParent():getContext(), M04_5Dialog.this);
				//dialogReason.show();
				//dismiss();
			}
		});
		
		btnSharePhoto = (Button) findViewById(R.id.m04_6_btnSharePhoto);
		btnSharePhoto.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bundle.putString(Constant.URL, StringUtil.getPhotoDetailLink(M04_5Dialog.this.photo.getUrl_id()));
				bundle.putString(Constant.URL_PHOTO, StringUtil.processImageLink(M04_5Dialog.this.photo.getUrl_photo()));
				bundle.putString(Constant.URL_THUMB, StringUtil.processImageLink(M04_5Dialog.this.photo.getUrl_thumb()));
				Intent i = new Intent(getContext(),M04_7Activity.class);
				i.putExtras(bundle);
				getContext().startActivity(i);
				dismiss();
			}

		});
		
		btnCancel = (Button) findViewById(R.id.m04_5_btnCancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dismiss();
			}
		});
	}
	
	private void saveImage() {
		AlertDialog.Builder salert = new AlertDialog.Builder(mContext);

		salert.setTitle(R.string.select_name);
		// Set an EditText view to get user input
		final EditText sinput = new EditText(mContext);
		sinput.setText(saveName);
		salert.setView(sinput);

		salert.setPositiveButton(mContext.getResources().getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if (sinput.getText().toString().length() != 0) {
							doSave(sinput.getText().toString(), false);
						} else {
							doSave(saveName, false);
						}
					}
				});

		salert.setNegativeButton(mContext.getResources().getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});

		salert.show();
	}
	public void doReportPhoto(String message){
		//@binhbt-comment
		//ReportPhotoRequest report = new ReportPhotoRequest("m04block", (Activity) mContext, message);
		//((MeshMapBaseActivity)mContext).getGlobalState().getRequestQueue().addRequest(report);
	}
	class ReportPhotoRequest extends RequestUI{
		private String message;
		private ReportErrors report;
		private Activity activity;
		public ReportPhotoRequest(Object key, Activity a, String mesage) {
			super(key, a);
			activity = a;
			// TODO Auto-generated constructor stub
			this.message = mesage;
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_id_report",currentUserId));
			nameValuePairs.add(new BasicNameValuePair("report_type", "2"));
			nameValuePairs.add(new BasicNameValuePair("report_message", message));
			nameValuePairs.add(new BasicNameValuePair("user_id_reported", blockId));
			nameValuePairs.add(new BasicNameValuePair("user_name_reported", photo.getUser().getUser_name()));
			nameValuePairs.add(new BasicNameValuePair("photo_id_reported", photo.getPhoto_id()));
			nameValuePairs.add(new BasicNameValuePair("photo_name_reported", "photo_name_reported"));
			GardenJokesApiConnect api = new GardenJokesApiConnect(activity);
			String result = api.execPost(mContext, GardenJokesApiConnect.GROUP_M, "report",
					nameValuePairs);
			Log.v("StringResult", result);
			JsonPaser jP = new JsonPaser();
			report = jP.getReport(result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			//do alert here
			Toast.makeText(mContext, report.getMessage(), 1000);
		}
		
	}
	
	/**
	 * Save image and share if doShare is true
	 * 
	 * @param fname
	 * @param doShare
	 */
	private void doSave(String fname, boolean doShare) {
		String photoUrl = this.photo.getUrl_photo();
		String filename = String.valueOf(photoUrl.hashCode());
		//String base = Environment.getExternalStorageDirectory()
		//.getAbsolutePath().toString();
		File file = new File(StorageUtils.getIndividualCacheDirectory(
				mContext).getAbsolutePath()
				+ "/" + filename);
		if (file.exists()) {
			imagePath = StorageUtils.getIndividualCacheDirectory(
					mContext).getAbsolutePath()
					+ "/" + filename;
		} else {
			return;
		}
		CharSequence text = mContext.getResources().getString(R.string.image_saved_as)
				+ " ";
		try {
			String ReservedChars = "|\\?*<\":>+[]/'";
			for (char c : ReservedChars.toCharArray()) {
				fname = fname.replace(c, '_');
			}
			String value = fname;
			Bitmap b = loadBitMap(imagePath);
			if (b == null) {
//				text = getResources().getString(R.string.image_save_fail_1);
//				Toast.makeText(this, text, Toast.LENGTH_LONG).show();
				return;
			}
			File folder = mContext.getFilesDir();
			if (externalStorageAvailable()) {
				try {
					folder = Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
					}
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment.getExternalStorageDirectory();
					}
				} catch (Exception e) {
					folder = Environment.getExternalStorageDirectory();
				} catch (Error e) {
					folder = Environment.getExternalStorageDirectory();
				}
				if (!folder.exists() || !folder.canWrite()) {
					folder = mContext.getFilesDir();
				}
			}
			
			String ext = ".jpg";
			String fullname = folder.getAbsolutePath() + File.separator + value
					+ ext;
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("filename", fullname);
			FileOutputStream fos;
			if (folder == mContext.getFilesDir())
				fos = mContext.openFileOutput(value + ext, Context.MODE_WORLD_WRITEABLE);
			else {
				File f2 = new File(fullname);// openFileOutput(fname,
												// Context.MODE_PRIVATE);//new
												// FileOutputStream(fullname);
				fos = new FileOutputStream(f2);
			}
			if (ext.equals(".png"))
				b.compress(CompressFormat.PNG, 95, fos);
			else
				b.compress(CompressFormat.JPEG, 95, fos);
			fos.close();
			String[] str = new String[1];
			str[0] = fullname;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
				MediaScannerConnection.scanFile(mContext, str, null, null);
			}
			text = text + value + ext + " "
					+ mContext.getResources().getString(R.string.saved_end);
			saveName = value;
			// setDetailTitle ();
			if (doShare) {
				Intent share = new Intent(Intent.ACTION_SEND);
				if (photo.getUrl_photo() != Constant.NO_COMIC) {
					share.setType("image/*");
				} else {
					share.setType("text/plain");
				}
				share.putExtra(Intent.EXTRA_TITLE, mContext.getResources()
						.getString(R.string.share_jorke));
				share.putExtra(Intent.EXTRA_TEXT, photo.getCaption());
				share.putExtra(Intent.EXTRA_STREAM,
						Uri.parse("file://" + fullname.replace(" ", "%20")));
				

				mContext.startActivity(Intent.createChooser(share, mContext.getResources()
						.getString(R.string.share_jorke)));
			}
		} catch (Exception e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
//			text = getResources().getString(R.string.image_save_fail_2)
//					+ e.toString();
		} catch (Error e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
//			text = getResources().getString(R.string.image_save_fail_2)
//					+ e.toString();
		}
		Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
	}
	private boolean externalStorageAvailable() {
		boolean mExternalStorageAvailable;
		boolean mExternalStorageWriteable;
		String state = Environment.getExternalStorageState();

		if (state.equals(Environment.MEDIA_MOUNTED)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		return mExternalStorageAvailable && mExternalStorageWriteable;
	}
	private Bitmap loadBitMap(String filrPath) {
		return BitmapFactory.decodeFile(filrPath);
	}
}
